#pragma semicolon 1
#pragma newdecls required

#include <sourcemod>
#include <left4dhooks>


#define PLUGIN_VERSION "1.0"


public Plugin myinfo =
{
	name = "l4d2_tank_leap_teleport",
	author = "豆瓣酱な",
	description = "Tank玩家输入!LP可随机传送至任意幸存者身边,每只Tank仅限使用1次.",
	version = PLUGIN_VERSION,
	url = "https://gitee.com/sweet-and-sour-bombs/adfvsdsd"
};


bool g_bHasTeleported[MAXPLAYERS + 1];

public void OnPluginStart()
{
	RegConsoleCmd("sm_lp", Command_LeapTeleport);
	
	HookEvent("tank_spawn", Event_TankSpawn);
}

public Action Event_TankSpawn(Event event, const char[] name, bool dontBroadcast)
{
	int client = GetClientOfUserId(event.GetInt("userid"));
	
	if (IsValidClient(client) && IsPlayerTank(client))
	{
		g_bHasTeleported[client] = false;
	}
	return Plugin_Handled;	
}

bool IsPlayerTank(int client)
{
	if (!IsValidClient(client)) return false;
	
	char classname[32];
	GetClientModel(client, classname, sizeof(classname));
	
	return (StrContains(classname, "hulk", false) != -1 || 
			StrContains(classname, "tank", false) != -1);
}

bool IsValidClient(int client)
{
	return (client > 0 && client <= MaxClients && 
			IsClientInGame(client) && 
			IsPlayerAlive(client));
}

public Action Command_LeapTeleport(int client, int args)
{
	if (!IsValidClient(client))
	{
		ReplyToCommand(client, "\x04[传送] \x03你必须活着才能使用此命令");
		return Plugin_Handled;
	}
	
	if (GetClientTeam(client) != 3 || !IsPlayerTank(client))
	{
		ReplyToCommand(client, "\x04[传送] \x03只有Tank可以使用此命令");
		return Plugin_Handled;
	}
	
	if (g_bHasTeleported[client])
	{
		ReplyToCommand(client, "\x04[传送] \x03每只Tank只能使用一次传送");
		return Plugin_Handled;
	}
	
	int[] survivors = new int[MaxClients];
	int survivorCount = 0;
	
	for (int i = 1; i <= MaxClients; i++)
	{
		if (IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2)
		{
			survivors[survivorCount++] = i;
		}
	}
	
	if (survivorCount == 0)
	{
		ReplyToCommand(client, "\x04[传送] \x03没有存活的幸存者可传送");
		return Plugin_Handled;
	}
	
	int randomSurvivor = survivors[GetRandomInt(0, survivorCount - 1)];
	
	float survivorPos[3];
	GetClientAbsOrigin(randomSurvivor, survivorPos);
	
	survivorPos[2] += 5.0; // 稍微抬高一点防止卡住
	
	// 强制Tank蹲下
	SetEntProp(client, Prop_Send, "m_bDucked", 1);
	SetEntityFlags(client, GetEntityFlags(client)|FL_DUCKING);
	
	TeleportEntity(client, survivorPos, NULL_VECTOR, NULL_VECTOR);
	
	g_bHasTeleported[client] = true;
	
	PrintToChatAll("\x04[传送] Tank \x03%N \x04传送到了 \x03%N \x04身边!", client, randomSurvivor);
	
	return Plugin_Handled;
}